import chalk from 'chalk';
import { SftpClient } from './sftp-client';
import { ServerConfig } from './types';
import { readJSON } from 'fs-extra';
import { getFiles } from './Utils';

export async function upload(config: ServerConfig, files: string[]) {

  try {
    console.log(chalk.green('Starting upload process...'));

    // Initialize SFTP client
    const sftpClient = new SftpClient(config);
    await sftpClient.connect()
    // Upload files
    const results = await sftpClient.uploadFolder({ remotePath: config.remotePath, localPath: config.localPath }, files);
    console.log(`Upload completed. ${results.filter(r => r.success).length}/${results.length} files transferred successfully`);
  } catch (err) {
    console.log(chalk.red('Fatal error in main process:', err));
    process.exit(1);
  }
}


export async function uploadFolder(configPath: string) {
  try {
    let serverConfig = await readJSON(configPath + ".json") as ServerConfig
    let files = await getFiles(serverConfig.localPath)

    console.log(chalk.green('Starting upload process...'));

    // Initialize SFTP client
    const sftpClient = new SftpClient(serverConfig);
    await sftpClient.connect()
    // Upload files
    const results = await sftpClient.uploadFolder({ remotePath: serverConfig.remotePath, localPath: serverConfig.localPath }, files);
    console.log(`Upload completed. ${results.filter(r => r.success).length}/${results.length} files transferred successfully`);
  } catch (err) {
    console.log(chalk.red('Fatal error in main process:', err));
    process.exit(1);
  }
}

// "upload": {
//     "host": "81.71.19.253",
//     "username": "client",
//     "password": "uo:FJDE=+8r#",
//     "port": 22,
//     "remotePath": "/home/client/gf_client_game/ver"
// },